package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.NumberFormatUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.MemberConverter;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.UserLoginRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.service.ILoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.List;

/**
 * 创建日期: 2022/05/19 11:27
 *
 * @author JinLu Zhou
 */
@Service
@Slf4j
public class LoginServiceImpl implements ILoginService {

    @Value("${custom.value}")
    private String cookieMaxAge;

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    MemberConverter memberConverter;

    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest, HttpServletResponse response) {
        UserLoginResponse userLoginResponse = new UserLoginResponse();
        try {
            String userName = userLoginRequest.getUserName();
            String password = DigestUtils.md5DigestAsHex(userLoginRequest.getPassword().getBytes());
            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username", userName)
                    .andEqualTo("password", password);
            List<Member> members = memberMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(members)) {
                throw new ValidateException(UserRetCode.USERORPASSWORD_ERRROR.getCode(),
                        UserRetCode.USERORPASSWORD_ERRROR.getMessage());
            }

            //判断是否认证
            Member member = members.get(0);
            if ("N".equals(member.getIsVerified())) {
                userLoginResponse.setMsg(UserRetCode.USER_ISVERFIED_ERROR.getMessage());
                userLoginResponse.setCode(UserRetCode.USER_ISVERFIED_ERROR.getCode());
                return userLoginResponse;
            }
            //登录成功
<<<<<<< HEAD
            //将一个对象设为token
            HashMap<String, Object> map = new HashMap<>();
            map.put("uid",member.getId());
            map.put("username",member.getUsername());
            JSONObject jsonObject = new JSONObject(map);
            String token = JwtTokenUtils.builder().msg(jsonObject.toString()).build().creatJwtToken();
=======
            HashMap<String, Object> map = new HashMap<>();
            map.put("uid", member.getId());
            map.put("username", member.getUsername());

            JSONObject object = new JSONObject(map);
            String token = JwtTokenUtils.builder().msg(object.toString()).build().creatJwtToken();
>>>>>>> 1864a7f3ee87996cfdb2da904951f8e527f711eb

            Cookie cookie = CookieUtil.genCookie("access_token", token, "/", NumberFormatUtil.getMaxAge(cookieMaxAge));

            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            userLoginResponse = memberConverter.memberToUserLoginResponse(member);
            userLoginResponse.setMsg(UserRetCode.SUCCESS.getMessage());
            userLoginResponse.setCode(UserRetCode.SUCCESS.getCode());
            userLoginResponse.setToken(token);
        } catch (Exception e) {
            log.error("LoginServiceImpl.login occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(userLoginResponse, e);
        }
        return userLoginResponse;
    }

    @Override
    public UserLoginResponse login(HttpServletRequest request) {

        UserLoginResponse userLoginResponse = new UserLoginResponse();
        try {

            String userInfo = request.getHeader("user_info");
            JSONObject object = JSON.parseObject(userInfo);
            Long uid = Long.parseLong(object.get("uid").toString());
            Member member = memberMapper.selectByPrimaryKey(uid);
<<<<<<< HEAD
=======
            // String userInfo = request.getHeader("user_info");
            // Member member = memberMapper.selectByPrimaryKey(userInfo);
>>>>>>> 1864a7f3ee87996cfdb2da904951f8e527f711eb
            if(member==null){
                userLoginResponse.setMsg(UserRetCode.DATA_NOT_EXIST.getMessage());
                userLoginResponse.setCode(UserRetCode.DATA_NOT_EXIST.getCode());
                return userLoginResponse;
            }
            userLoginResponse = memberConverter.memberToUserLoginResponse(member);
            userLoginResponse.setMsg(UserRetCode.SUCCESS.getMessage());
            userLoginResponse.setCode(UserRetCode.SUCCESS.getCode());
        } catch (Exception e) {
            log.error("LoginServiceImpl.login occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(userLoginResponse, e);
        }
        return userLoginResponse;
    }
}
